import 'dart:ui';

import 'package:custom_widgets/widget/gradual_change_view.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:like_button/like_button.dart';
import 'package:mi_mang_flutter/api/daily_words_api.dart';
import 'package:mi_mang_flutter/api/favorite_words_api.dart';
import 'package:mi_mang_flutter/model/daily_word_model.dart';
import 'package:mi_mang_flutter/network_other/api_service.dart';
import 'package:mi_mang_flutter/network_other/weather_bean.dart';
import 'package:mi_mang_flutter/page/home/home_router.dart';
import 'package:mi_mang_flutter/page/login/login_router.dart';
import 'package:mi_mang_flutter/page/setting/setting_router.dart';
import 'package:mi_mang_flutter/provider/user_provider.dart';
import 'package:mi_mang_flutter/res/dimens.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:mi_mang_flutter/utils/shared_preferences.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:custom_widgets/custom_widgets.dart';
import 'package:mi_mang_flutter/utils/utils.dart';
import 'package:provider/provider.dart';

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  DailyWordModel? model;
  WeatherBean? weatherBean;

  String city = ' --';

  @override
  void initState() {
    super.initState();

    var modelMap = SpUtil.getObject(SPKeys.HOME_DAILY_KEY);
    if (modelMap != null) {
      model = DailyWordModel.fromJson(modelMap);
    }

    // 单次Frame绘制回调(addPostFrameCallback)
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 该处由于网络请求的问题,导致请求数据解析不了(首次进入App时,无网络导致)
      DailyWordsApi.getDailyWordsPage(pageNum: 1, pageSize: 1).then((val) {
        setState(() {
          model = val.data!.records!.first;
        });
      }).catchError((error) {
        setState(() {});
      });
      ApiService.instance!.getWeatherNow(
          success: (WeatherBean weather, String? locality) {
        setState(() {
          city = locality ?? '--';
          weatherBean = weather;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: DoubleTapBackExitApp(
        child: Scaffold(
          body: Stack(
            children: <Widget>[
              ConstrainedBox(
                // 限制条件，可扩展的
                constraints: BoxConstraints.expand(),
                child: loadNetworkImage(
                  model?.imageUrl ?? '',
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                bottom: 0.0,
                left: 0.0,
                right: 0.0,
                child: GradualChangeView(
                  height: 600.0,
                  rotation: Rotation.TB,
                  colors: [Colors.transparent, Colors.white24],
                ),
              ),
              Positioned.fill(
                child: ClipRect(
                  // 背景过滤器
                  child: BackdropFilter(
                    filter: ImageFilter.blur(
                      sigmaX: 1.0,
                      sigmaY: 1.0,
                    ),
                    child: InkWell(
                      onTap: () {
                        Utils.feedbackVibrate();
                        NavigatorUtils.push(
                          context,
                          HomeRouter.dailyPicture,
                          // transitionDuration: Duration(milliseconds: 500),
                          transition: TransitionType.fadeIn,
                        );
                      },
                      child: Container(
                        color: Colors.white12,
                      ),
                    ),
                  ),
                ),
              ),
              _buildBody(),
            ],
          ),
        ),
        showMessage: () {
          Toast.showInfo("再次点击退出应用");
        },
      ),
    );
  }

  /// 主题内容布局
  Widget _buildBody() {
    return Column(
      children: <Widget>[
        _buildAppBar(),
        _buildContent(),
        Spacer(),
        _buildBottom(),
        Gaps.vBottomBarHeight,
      ],
    );
  }

  Widget _buildAppBar() {
    return SafeArea(
      bottom: false,
      child: Container(
        padding: EdgeInsets.only(right: 15.0),
        height: AppBar().preferredSize.height,
        alignment: Alignment.centerRight,
        child: Material(
          color: Colors.transparent,
          shape: CircleBorder(),
          clipBehavior: Clip.hardEdge,
          child: IconButton(
            tooltip: i18n(context).setting,
            splashColor: Colors.white24,
            icon: Icon(
              Icons.settings,
              size: 26.0,
              color: Colors.white,
            ),
            onPressed: () {
              NavigatorUtils.push(context, SettingRouter.setting);
            },
          ),
        ),
      ),
    );
  }

  /// 主体内容布局
  Widget _buildContent() {
    String weather = weatherBean?.now?.text ?? '--';
    return Consumer<UserProvider>(builder: (context, provider, _) {
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: Dimens.gapDp25),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "${_showDate(context)} $city ${i18n(context).weather}：$weather",
              style: TextStyle(
                fontSize: 20.0,
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
            Gaps.vGap15,
            Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    _showTime(context),
                    style: TextStyle(
                      fontSize: 28.0,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Visibility(
                  visible: provider.user == null,
                  child: MaterialButton(
                    height: 35.0,
                    elevation: 0.0,
                    child: Text(
                      i18n(context).leaveLogin,
                      style: TextStyle(
                        fontSize: 15.0,
                        color: Colors.black87,
                      ),
                    ),
                    color: Colors.white54,
                    shape: StadiumBorder(),
                    onPressed: () {
                      NavigatorUtils.push(
                        context,
                        LoginRouter.login,
                      );
                    },
                  ),
                ),
                Visibility(
                  visible: provider.user != null,
                  child: Text(
                    provider.user?.nickName ?? i18n(context).editInfo,
                    style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.white,
                    ),
                  ),
                ),
                Gaps.hGap15,
                InkWell(
                  onTap: () {
                    if (provider.user != null) {
                      NavigatorUtils.push(context, SettingRouter.personalInfo);
                    } else {
                      NavigatorUtils.push(
                        context,
                        LoginRouter.login,
                      );
                    }
                  },
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      border:
                          Border.all(color: Colors.white24, width: 5.0), //边框
                      shape: BoxShape.circle,
                    ),
                    child: ClipOval(
                      child: loadNetworkImage(
                        provider.user?.avatar ?? '',
                        placeholder: "public/default_user",
                        width: 72.0,
                        height: 72.0,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Gaps.vGap12,
            Visibility(
              visible: provider.user != null,
              child: Container(
                alignment: Alignment.centerRight,
                child: MaterialButton(
                  height: 35.0,
                  elevation: 0.0,
                  child: Text(
                    i18n(context).myCollect,
                    style: TextStyle(
                      fontSize: 14.0,
                      color: Colors.black54,
                    ),
                  ),
                  color: Colors.white60,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(20.0))),
                  onPressed: () {
                    NavigatorUtils.push(context, HomeRouter.collection);
                  },
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 底部每日一句布局
  Widget _buildBottom() {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: Dimens.gapDp25,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            model?.content ?? "",
            style: Theme.of(context).textTheme.titleMedium!.copyWith(
                  height: 1.2,
                  color: Colors.white,
                ),
          ),
          Gaps.vGap8,
          Text(
            "—— ${model?.source ?? ''}",
            style: Theme.of(context).textTheme.titleMedium!.copyWith(
                  color: Colors.white,
                ),
          ),
          _buildButton(),
          Gaps.vGap5,
        ],
      ),
    );
  }

  /// 点赞按钮布局
  Widget _buildButton() {
    return Container(
      height: Dimens.gapDp35,
      child: LikeButton(
        mainAxisAlignment: MainAxisAlignment.end,
        likeBuilder: (bool isLiked) {
          return Icon(
            isLiked ? Icons.favorite : Icons.favorite_border,
            color: isLiked ? const Color(0xFFF44336) : Colors.white,
            size: Dimens.gapDp25,
          );
        },
        countPostion: CountPostion.left,
        likeCount: model?.favCount ?? 0,
        likeCountPadding: const EdgeInsets.only(right: 8.0),
        countBuilder: (int? count, bool isLiked, String text) {
          return Text(
            text,
            textScaler: TextScaler.linear(1.0),
            style: TextStyle(
              fontSize: 16.0,
              color: Colors.white,
            ),
          );
        },
        isLiked: model?.isFav ?? false,
        onTap: (isLiked) {
          Utils.feedbackVibrate();
          if (isLiked) {
            return _favoriteWordsRemove();
          } else {
            return _favoriteWordsSave();
          }
        },
      ),
    );
  }

  /// 区分时间段
  String _showTime(BuildContext context) {
    String value = i18n(context).goodMorning;
    int hour = DateTime.now().hour;
    if (hour >= 5 && hour < 8) {
      value = i18n(context).goodMorning;
    } else if (hour >= 8 && hour < 12) {
      value = i18n(context).morning;
    } else if (hour >= 12 && hour < 14) {
      value = i18n(context).goodAfternoon;
    } else if (hour >= 14 && hour < 18) {
      value = i18n(context).afternoon;
    } else {
      value = i18n(context).goodNight;
    }
    return value;
  }

  /// 显示日期
  String _showDate(BuildContext context) {
    return "${DateTime.now().month}月${DateTime.now().day}日";
  }

  /// 点赞
  /// 返回true则更改为取消收藏状态
  Future<bool> _favoriteWordsSave() async {
    var response =
        await FavoriteWordsApi.favoriteWordsSave(model?.id ?? '' as int);
    // 判断请求是否成功, 请求成功则更新点赞状态为true
    model!.isFav = response.data == true;
    if (model!.favCount != null) {
      model!.favCount = model!.favCount! + 1;
    }

    SpUtil.putObject(SPKeys.HOME_DAILY_KEY, model);
    return Future.value(model!.isFav);
  }

  /// 取消点赞
  /// 返回false则更改为取消收藏状态
  Future<bool> _favoriteWordsRemove() async {
    var response =
        await FavoriteWordsApi.favoriteWordsRemove(model?.id ?? '' as int);
    // 判断请求是否成功, 请求成功则更新点赞状态为false
    model!.isFav = !(response.data == true);
    if (model?.favCount != null) {
      model!.favCount = model!.favCount! - 1;
    }
    SpUtil.putObject(SPKeys.HOME_DAILY_KEY, model);
    return Future.value(model!.isFav);
  }
}
